package com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.bean.LimsQualitycontrolplanProjectBean;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.dao.LimsQualitycontrolplanProjectDao;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.service.LimsQualitycontrolplanProjectService;
import com.sunwayworld.basemodule.business.qualitycontrol.qualityrule.bean.LimsQualityRuleBean;
import com.sunwayworld.basemodule.business.qualitycontrol.qualityrule.service.LimsQualityRuleService;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.data.page.Page;
import com.sunwayworld.framework.data.page.Pagination;
import com.sunwayworld.framework.exception.UnsupportedException;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.mybatis.page.MybatisPageHelper;
import com.sunwayworld.framework.mybatis.page.PageRowBounds;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.support.PersistableHelper;
import com.sunwayworld.framework.utils.ClassUtils;
import com.sunwayworld.framework.utils.CollectionUtils;
import com.sunwayworld.framework.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsQualitycontrolplanProjectServiceImpl implements LimsQualitycontrolplanProjectService {

    @Autowired
    private LimsQualitycontrolplanProjectDao limsQualitycontrolplanProjectDao;

    @Autowired
    private LimsQualityRuleService limsQualityRuleService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsQualitycontrolplanProjectDao getDao() {
        return limsQualitycontrolplanProjectDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsQualitycontrolplanProjectBean limsQualitycontrolplanProject = jsonWrapper.parseUnique(LimsQualitycontrolplanProjectBean.class);
        limsQualitycontrolplanProject.setId(ApplicationContextHelper.getNextIdentity());
        getDao().insert(limsQualitycontrolplanProject);
        return limsQualitycontrolplanProject.getId();
    }

    @Override
    public JSONObject getControlRuleSelections(RestJsonWrapperBean jsonWrapperBean) {
        List<LimsQualityRuleBean> ruleBeanList = limsQualityRuleService.selectAll();
        JSONObject req = new JSONObject();
        JSONArray items = new JSONArray();
        Collections.sort(ruleBeanList);
        ruleBeanList.forEach(i -> {
            JSONObject temp = new JSONObject();
            temp.put("value", String.valueOf(i.getId()));
            temp.put("text", i.getRuleName());
            items.add(temp);
        });
        req.put("items", items);
        return req;
    }

/*    @Override
    public Page<LimsQualitycontrolplanProjectBean> selectPagination(MapperParameter parameter, PageRowBounds rowBounds) {
        List<Map<String, Object>> results = getDao().selectByCondition(parameter);
        results.forEach(i -> {
            System.out.println(i);
            if (i.containsKey("controlRule".toUpperCase()) && i.get("controlRule".toUpperCase()) != null) {
                List<String> controlRuleIds = Arrays.asList(String.valueOf(i.get("controlRule".toUpperCase())).split(","));
                List<LimsQualityRuleBean> ruleBeanList = limsQualityRuleService.selectListByFilter(SearchFilter.instance().match("id", controlRuleIds).filter(MatchPattern.OR));
                if (!ruleBeanList.isEmpty()) {
                    Collections.sort(ruleBeanList);
                    String controlRuleName = StringUtils.join(ruleBeanList.stream().map(LimsQualityRuleBean::getRuleName).collect(Collectors.toList()), ",");
                    System.out.println(controlRuleName);
                    i.put("controlRuleName", controlRuleName);
                } else {
                    i.put("controlRuleName", "");
                }
            }
        });
        return selectPagination(() -> results, rowBounds);
    }*/

    @Override
    public <V> Page<LimsQualitycontrolplanProjectBean> selectPagination(Supplier<List<V>> mapOrItemSupplier, PageRowBounds rowBounds) {
        Page<V> page = MybatisPageHelper.get(rowBounds, mapOrItemSupplier);

        if (page.getRows().isEmpty()) {
            return new Pagination<>(page, CollectionUtils.emptyList());
        }

        Class<V> clazz = (Class<V>) ClassUtils.getRawType(page.getRows().get(0).getClass());

        if (Map.class.isAssignableFrom(clazz)) {
            List<LimsQualitycontrolplanProjectBean> itemList = page.getRows().parallelStream().map(m -> PersistableHelper.mapToPersistable((Map<String, Object>) m, getDao().getType())).collect(Collectors.toList());
            itemList.forEach(i -> {
                if (i.getControlRule() != null) {
                    List<String> controlRuleIds = Arrays.asList(i.getControlRule().split(","));

                    List<LimsQualityRuleBean> ruleBeanList = limsQualityRuleService.selectListByFilter(SearchFilter.instance().match("id", controlRuleIds).filter(MatchPattern.OR));
                    if (!ruleBeanList.isEmpty()) {
                        Collections.sort(ruleBeanList);
                        String controlRuleName = StringUtils.join(ruleBeanList.stream().map(LimsQualityRuleBean::getRuleName).collect(Collectors.toList()), ",");
                        i.setExt$Item("controlrulename", controlRuleName);
                    } else {
                        i.setExt$Item("controlrulename", "");
                    }
                }
            });
            return new Pagination<>(page, itemList);
        } else if (getDao().getType().isAssignableFrom(clazz)) {
            return (Page<LimsQualitycontrolplanProjectBean>) page;
        }

        throw new UnsupportedException();
    }
}
